package com.lhy.framework.core.io;

import cn.hutool.core.lang.Assert;
import com.lhy.framework.utils.ClassUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Title:
 * @Description: 功能概述: 类文件加载
 * @Author: lihaiyang
 * @version: 1.0 .
 * @Date: 2022-09-09 09:38
 * @Copyright: Copyright(c)2022 RedaFlight.comAll Rights Reserved
 */
public class ClassPathResource implements Resource {

    private final String path;

    private final ClassLoader classLoader;

    public ClassPathResource(String path) {
        this(path, null);
    }

    public ClassPathResource(String path, ClassLoader classLoader) {
        Assert.notNull(path, "path must not be null");
        this.path = path;
        this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
    }


    @Override
    public InputStream getInputStream() throws IOException {
        InputStream is = classLoader.getResourceAsStream(path);
        if (is == null) {
            throw new FileNotFoundException(this.path + " cannot be opened because it does not exist");
        }
        return is;
    }
}
